import wiringpi as gpio
import datetime


class ds1307(object):
  addr = None
  fd = None
  def __init__(self, addr=0x68):
    self.addr = addr
    self.fd = gpio.wiringPiI2CSetup(self.addr)

  def read_rtc(self, reg):
    return gpio.wiringPiI2CReadReg8(self.fd, reg)

  def wirte_rtc(self, reg, data):
    return gpio.wiringPiI2CWriteReg8(self.fd, reg, data)

  def is_ch(self):
    return self.read_rtc(0) >> 7 == 1

  @property
  def second(self):
    val = self.read_rtc(0)
    return ((val & 0x70) >> 4) * 10 + (val & 0x0F)
  
  @property
  def minute(self):
    val = self.read_rtc(1)
    return ((val & 0x70) >> 4) * 10 + (val & 0x0F)

  @property
  def hour(self):
    val = self.read_rtc(2)
    is12 = (val >> 6) & 0x1 == 1
    if is12:
      am_pm = (val >> 5) & 0x1
      h = ((val & 0x10) >> 4) * 10 + (val & 0x0F)
      return (am_pm, h)
    else:
      return ((val & 0x30) >> 4) * 10 + (val & 0x0F)

  @property
  def week(self):
    return self.read_rtc(3) & 0x07

  @property
  def day(self):
    val = self.read_rtc(4)
    return ((val & 0x30) >> 4) * 10 + (val & 0x0F)

  @property
  def month(self):
    val = self.read_rtc(5)
    return ((val & 0x10) >> 4) * 10 + (val & 0x0F)

  @property
  def year(self):
    val = self.read_rtc(6)
    return ((val & 0xF0) >> 4) * 10 + (val & 0x0F)

  @property
  def date_time(self):
    return datetime.datetime(1970+self.year, self.month, self.day, self.hour, self.minute, self.second)


if __name__ == '__main__':
  ds = ds1307()
  print(ds.is_ch())
  while True:
    print('{}-{}-{} {}:{}:{}'.format(ds.year, ds.month, ds.day, ds.hour, ds.minute, ds.second))
    print(ds.date_time)
    gpio.delay(1000)
